package com.pingan.stat.reposys.general.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.pingan.common.core.property.Properties;
import com.pingan.common.util.ShellExecutor;
import com.pingan.setting.money24url.entity.Money24UrlBean;
import com.pingan.setting.money24url.service.Money24UrlSettingService;
import com.pingan.stat.service.StatService;

@Component
public class GeneralUrlStatService implements StatService {

	@Properties(name = "reposys.general.output.path")
	private String outputPath;

	@Properties(name = "reposys.general.url.stat")
	private String generalUrlStatShell;

	@Properties(name = "general.url.stat.hql.file")
	private String generalUrlStatCreateHQLShell;

	@Resource
	private Money24UrlSettingService money24UrlSettingService;

	@Resource
	private ShellExecutor shellExecutor;

	private static final Log log = LogFactory.getLog("hive");

	public void dailyStat(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String yyyyMMdd = sdf.format(date);
		String output = outputPath + "/" + yyyyMMdd;

		log.info("----------------->>>>>>>>>>>>>>>>>> stat 24money url");
		List<Money24UrlBean> beans = money24UrlSettingService
				.getStatMoney24Urls(date);

		for (Money24UrlBean bean : beans) {
			if (!StringUtils.startsWith(bean.getUrl(), "http://")) {
				bean.setUrl("http://" + bean.getUrl());
			}

			String hql = getHQL(yyyyMMdd, bean);

			log.info("-----> " + hql);

			String[] hqlParams = new String[] { hql };
			shellExecutor.excecute(generalUrlStatCreateHQLShell, hqlParams);

			String[] params = new String[] { yyyyMMdd, output,
					Integer.valueOf(bean.getId()).toString() };

			shellExecutor.excecute(generalUrlStatShell, params);
		}

	}

	public String getHQL(String yyyyMMdd, Money24UrlBean bean) {
		StringBuilder sb = new StringBuilder(
				"select log_date, count(*), count(distinct(juid)), count(distinct(ip)), count(distinct(sessionid)) ");
		boolean isUrl = true;

		if ("url".equals(bean.getUrlType())) {
			sb.append(" from " + bean.getSiteId() + ".pv where log_date='"
					+ yyyyMMdd + "' and ");
		} else {
			isUrl = false;
			sb.append(" from " + bean.getSiteId() + ".pv where log_date='"
					+ yyyyMMdd + "' and ");
		}

		if (bean.getMatchType() == 1) {
			if (isUrl) {
				sb.append(" url='" + bean.getUrl() + "' group by log_date");
			} else {
				sb.append(" referurl='" + bean.getUrl() + "' group by log_date");
			}
		} else {
			if (isUrl) {
				sb.append(" url like '" + bean.getUrl()
						+ "%' group by log_date");
			} else {
				sb.append(" referurl like '" + bean.getUrl()
						+ "%' group by log_date");
			}
		}

		return sb.toString();
	}
}
